package org.example.service;

import org.example.entity.User;
import org.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    private final UserRepository userRepository;


    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 根据用户名查询用户
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    // 注册新用户
    public void registerUser(String username, String password) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }


        // 确认password参数不为null（配合Controller的校验，双重保障）
        if (password == null || password.trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }

        // 创建并保存用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userRepository.save(user);
    }

    // 验证用户密码
    public boolean verifyPassword(User user, String rawPassword) {
        // 避免空指针异常：先判断两个字符串是否都不为空
        if (rawPassword == null || user.getPassword() == null) {
            return false;
        }

        return user.getPassword().equals(rawPassword);
    }
}

